/**
 * 景区管理面板组件
 * 提供景区、商铺、设施的完整管理界面
 */

'use client'

import React, { useState, useEffect } from 'react'
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Badge } from "@/components/ui/badge"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { toast } from 'sonner'
import { MapPin, Building, Wrench, Plus, Edit, Trash2, RefreshCw } from 'lucide-react'

// API导入
import { getAttractionsList, deleteAttraction } from '@/lib/api/attraction'
import { getStoresByAttraction, deleteStore } from '@/lib/api/store'
import { getFacilitiesByAttraction, deleteFacility } from '@/lib/api/facility'
import { getBusinessTypes, getStoreStatusOptions } from '@/lib/api/store'
import { getFacilityTypes, getFacilityStatusOptions } from '@/lib/api/facility'

// 组件导入
import { AttractionManagementModal } from './AttractionManagementModal'
import { StoreBindingModal } from './StoreBindingModal'
import { FacilityBindingModal } from './FacilityBindingModal'

interface AttractionManagementPanelProps {
  className?: string
  onAttractionSelect?: (attraction: any) => void
  onRefreshModel?: (attractionId: string) => void
}

export const AttractionManagementPanel: React.FC<AttractionManagementPanelProps> = ({
  className = '',
  onAttractionSelect,
  onRefreshModel
}) => {
  // 状态管理
  const [attractions, setAttractions] = useState<any[]>([])
  const [stores, setStores] = useState<any[]>([])
  const [facilities, setFacilities] = useState<any[]>([])
  const [selectedAttraction, setSelectedAttraction] = useState<string>('')
  const [isLoading, setIsLoading] = useState(false)

  // 模态框状态
  const [isAttractionModalOpen, setIsAttractionModalOpen] = useState(false)
  const [isStoreModalOpen, setIsStoreModalOpen] = useState(false)
  const [isFacilityModalOpen, setIsFacilityModalOpen] = useState(false)
  
  // 编辑状态
  const [editingAttraction, setEditingAttraction] = useState<any>(null)
  const [editingStore, setEditingStore] = useState<any>(null)
  const [editingFacility, setEditingFacility] = useState<any>(null)

  // 获取数据的辅助函数
  const businessTypes = getBusinessTypes()
  const storeStatusOptions = getStoreStatusOptions()
  const facilityTypes = getFacilityTypes()
  const facilityStatusOptions = getFacilityStatusOptions()

  // 加载景区列表
  const loadAttractions = async () => {
    setIsLoading(true)
    try {
      const result = await getAttractionsList()
      if (result.success && result.data) {
        setAttractions(result.data)
        if (result.data.length > 0 && !selectedAttraction) {
          setSelectedAttraction(result.data[0].id)
        }
      } else {
        toast.error(result.msg || '加载景区列表失败')
      }
    } catch (error) {
      console.error('加载景区列表失败:', error)
      toast.error('加载景区列表失败')
    } finally {
      setIsLoading(false)
    }
  }

  // 加载选中景区的商铺和设施
  const loadAttractionData = async (attractionId: string) => {
    if (!attractionId) return

    try {
      const [storesResult, facilitiesResult] = await Promise.all([
        getStoresByAttraction(attractionId),
        getFacilitiesByAttraction(attractionId)
      ])

      if (storesResult.success && storesResult.data) {
        setStores(storesResult.data)
      }

      if (facilitiesResult.success && facilitiesResult.data) {
        setFacilities(facilitiesResult.data)
      }
    } catch (error) {
      console.error('加载景区数据失败:', error)
      toast.error('加载景区数据失败')
    }
  }

  // 初始化和响应选择变化
  useEffect(() => {
    loadAttractions()
  }, [])

  useEffect(() => {
    if (selectedAttraction) {
      loadAttractionData(selectedAttraction)
      const attraction = attractions.find(a => a.id === selectedAttraction)
      onAttractionSelect?.(attraction)
    }
  }, [selectedAttraction, attractions])

  // 删除操作
  const handleDeleteAttraction = async (id: string) => {
    if (!confirm('确定要删除这个景区吗？这将同时删除相关的商铺和设施数据。')) {
      return
    }

    try {
      const result = await deleteAttraction(id)
      if (result.success) {
        toast.success(result.msg)
        loadAttractions()
        if (selectedAttraction === id) {
          setSelectedAttraction('')
        }
      } else {
        toast.error(result.msg)
      }
    } catch (error) {
      console.error('删除景区失败:', error)
      toast.error('删除景区失败')
    }
  }

  const handleDeleteStore = async (id: string) => {
    if (!confirm('确定要删除这个商铺吗？')) {
      return
    }

    try {
      const result = await deleteStore(id)
      if (result.success) {
        toast.success(result.msg)
        loadAttractionData(selectedAttraction)
      } else {
        toast.error(result.msg)
      }
    } catch (error) {
      console.error('删除商铺失败:', error)
      toast.error('删除商铺失败')
    }
  }

  const handleDeleteFacility = async (id: string) => {
    if (!confirm('确定要删除这个设施吗？')) {
      return
    }

    try {
      const result = await deleteFacility(id)
      if (result.success) {
        toast.success(result.msg)
        loadAttractionData(selectedAttraction)
      } else {
        toast.error(result.msg)
      }
    } catch (error) {
      console.error('删除设施失败:', error)
      toast.error('删除设施失败')
    }
  }

  // 编辑操作
  const handleEditAttraction = (attraction: any) => {
    setEditingAttraction(attraction)
    setIsAttractionModalOpen(true)
  }

  const handleEditStore = (store: any) => {
    setEditingStore(store)
    setIsStoreModalOpen(true)
  }

  const handleEditFacility = (facility: any) => {
    setEditingFacility(facility)
    setIsFacilityModalOpen(true)
  }

  // 成功回调
  const handleAttractionSuccess = () => {
    loadAttractions()
    setEditingAttraction(null)
  }

  const handleStoreSuccess = () => {
    loadAttractionData(selectedAttraction)
    setEditingStore(null)
    onRefreshModel?.(selectedAttraction)
  }

  const handleFacilitySuccess = () => {
    loadAttractionData(selectedAttraction)
    setEditingFacility(null)
  }

  // 获取业务类型标签
  const getBusinessTypeLabel = (value: string) => {
    const type = businessTypes.find(t => t.value === value)
    return type ? `${type.icon} ${type.label}` : value
  }

  // 获取设施类型标签
  const getFacilityTypeLabel = (value: string) => {
    const type = facilityTypes.find(t => t.type === value)
    return type ? `${type.icon} ${type.label}` : value
  }

  // 获取状态颜色
  const getStatusColor = (status: string, type: 'store' | 'facility') => {
    const options = type === 'store' ? storeStatusOptions : facilityStatusOptions
    const option = options.find(o => o.value === status)
    return option?.color || '#6b7280'
  }

  return (
    <div className={`space-y-4 ${className}`}>
      {/* 头部操作栏 */}
      <Card>
        <CardHeader className="pb-3">
          <div className="flex items-center justify-between">
            <CardTitle className="text-lg">景区数据管理</CardTitle>
            <div className="flex items-center gap-2">
              <Button
                size="sm"
                onClick={() => setIsAttractionModalOpen(true)}
                className="gap-1"
              >
                <Plus className="w-4 h-4" />
                新增景区
              </Button>
              {selectedAttraction && (
                <Button
                  size="sm"
                  variant="outline"
                  onClick={() => onRefreshModel?.(selectedAttraction)}
                  className="gap-1"
                >
                  <RefreshCw className="w-4 h-4" />
                  刷新模型
                </Button>
              )}
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <div className="flex items-center gap-3">
            <label className="text-sm font-medium whitespace-nowrap">
              当前景区：
            </label>
            <Select value={selectedAttraction} onValueChange={setSelectedAttraction}>
              <SelectTrigger className="w-64">
                <SelectValue placeholder="选择景区" />
              </SelectTrigger>
              <SelectContent>
                {attractions.map((attraction) => (
                  <SelectItem key={attraction.id} value={attraction.id}>
                    {attraction.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </CardContent>
      </Card>

      {/* 主要内容区域 */}
      {selectedAttraction ? (
        <Tabs defaultValue="attractions" className="space-y-4">
          <TabsList className="grid w-full grid-cols-3">
            <TabsTrigger value="attractions" className="gap-2">
              <Building className="w-4 h-4" />
              景区管理
            </TabsTrigger>
            <TabsTrigger value="stores" className="gap-2">
              <MapPin className="w-4 h-4" />
              商铺管理
            </TabsTrigger>
            <TabsTrigger value="facilities" className="gap-2">
              <Wrench className="w-4 h-4" />
              设施管理
            </TabsTrigger>
          </TabsList>

          {/* 景区管理 */}
          <TabsContent value="attractions">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center justify-between">
                  景区列表
                  <Badge variant="secondary">{attractions.length} 个景区</Badge>
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  {attractions.map((attraction) => (
                    <div
                      key={attraction.id}
                      className="flex items-center justify-between p-3 border rounded-lg"
                    >
                      <div className="flex-1">
                        <div className="font-medium">{attraction.name}</div>
                        <div className="text-sm text-gray-500 mt-1">
                          {attraction.description}
                        </div>
                        <div className="text-xs text-gray-400 mt-1">
                          中心坐标: {attraction.center[0].toFixed(4)}, {attraction.center[1].toFixed(4)}
                        </div>
                        {attraction.floors.length > 0 && (
                          <div className="flex gap-1 mt-2">
                            {attraction.floors.map((floor: string) => (
                              <Badge key={floor} variant="outline" className="text-xs">
                                {floor}
                              </Badge>
                            ))}
                          </div>
                        )}
                      </div>
                      <div className="flex items-center gap-2 ml-4">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleEditAttraction(attraction)}
                        >
                          <Edit className="w-4 h-4" />
                        </Button>
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleDeleteAttraction(attraction.id)}
                          className="text-red-600 hover:text-red-700"
                        >
                          <Trash2 className="w-4 h-4" />
                        </Button>
                      </div>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* 商铺管理 */}
          <TabsContent value="stores">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center justify-between">
                  商铺列表
                  <div className="flex items-center gap-2">
                    <Badge variant="secondary">{stores.length} 个商铺</Badge>
                    <Button
                      size="sm"
                      onClick={() => setIsStoreModalOpen(true)}
                      className="gap-1"
                    >
                      <Plus className="w-4 h-4" />
                      新增商铺
                    </Button>
                  </div>
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  {stores.map((store) => (
                    <div
                      key={store.id}
                      className="flex items-center justify-between p-3 border rounded-lg"
                    >
                      <div className="flex-1">
                        <div className="flex items-center gap-2">
                          <span className="font-medium">{store.name}</span>
                          <Badge variant="outline">
                            {getBusinessTypeLabel(store.business)}
                          </Badge>
                          <div
                            className="w-2 h-2 rounded-full"
                            style={{ backgroundColor: getStatusColor(store.status, 'store') }}
                            title={storeStatusOptions.find(s => s.value === store.status)?.label}
                          />
                        </div>
                        {store.description && (
                          <div className="text-sm text-gray-500 mt-1">
                            {store.description}
                          </div>
                        )}
                        <div className="text-xs text-gray-400 mt-1">
                          位置: {store.position[0].toFixed(4)}, {store.position[1].toFixed(4)}
                        </div>
                        {store.contact?.phone && (
                          <div className="text-xs text-gray-400">
                            电话: {store.contact.phone}
                          </div>
                        )}
                      </div>
                      <div className="flex items-center gap-2 ml-4">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleEditStore(store)}
                        >
                          <Edit className="w-4 h-4" />
                        </Button>
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleDeleteStore(store.id)}
                          className="text-red-600 hover:text-red-700"
                        >
                          <Trash2 className="w-4 h-4" />
                        </Button>
                      </div>
                    </div>
                  ))}
                  {stores.length === 0 && (
                    <div className="text-center py-8 text-gray-500">
                      暂无商铺数据，点击"新增商铺"开始添加
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* 设施管理 */}
          <TabsContent value="facilities">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center justify-between">
                  设施列表
                  <div className="flex items-center gap-2">
                    <Badge variant="secondary">{facilities.length} 个设施</Badge>
                    <Button
                      size="sm"
                      onClick={() => setIsFacilityModalOpen(true)}
                      className="gap-1"
                    >
                      <Plus className="w-4 h-4" />
                      新增设施
                    </Button>
                  </div>
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  {facilities.map((facility) => (
                    <div
                      key={facility.id}
                      className="flex items-center justify-between p-3 border rounded-lg"
                    >
                      <div className="flex-1">
                        <div className="flex items-center gap-2">
                          <span className="font-medium">{facility.name}</span>
                          <Badge variant="outline">
                            {getFacilityTypeLabel(facility.type)}
                          </Badge>
                          <div
                            className="w-2 h-2 rounded-full"
                            style={{ backgroundColor: getStatusColor(facility.status, 'facility') }}
                            title={facilityStatusOptions.find(s => s.value === facility.status)?.label}
                          />
                        </div>
                        {facility.description && (
                          <div className="text-sm text-gray-500 mt-1">
                            {facility.description}
                          </div>
                        )}
                        <div className="text-xs text-gray-400 mt-1">
                          位置: {facility.position[0].toFixed(4)}, {facility.position[1].toFixed(4)}
                        </div>
                      </div>
                      <div className="flex items-center gap-2 ml-4">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleEditFacility(facility)}
                        >
                          <Edit className="w-4 h-4" />
                        </Button>
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleDeleteFacility(facility.id)}
                          className="text-red-600 hover:text-red-700"
                        >
                          <Trash2 className="w-4 h-4" />
                        </Button>
                      </div>
                    </div>
                  ))}
                  {facilities.length === 0 && (
                    <div className="text-center py-8 text-gray-500">
                      暂无设施数据，点击"新增设施"开始添加
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>
      ) : (
        <Card>
          <CardContent className="text-center py-8 text-gray-500">
            请先选择或创建一个景区
          </CardContent>
        </Card>
      )}

      {/* 模态框 */}
      <AttractionManagementModal
        isOpen={isAttractionModalOpen}
        onClose={() => {
          setIsAttractionModalOpen(false)
          setEditingAttraction(null)
        }}
        editingAttraction={editingAttraction}
        onSuccess={handleAttractionSuccess}
      />

      <StoreBindingModal
        isOpen={isStoreModalOpen}
        onClose={() => {
          setIsStoreModalOpen(false)
          setEditingStore(null)
        }}
        attractionId={selectedAttraction}
        editingStore={editingStore}
        onSuccess={handleStoreSuccess}
      />

      <FacilityBindingModal
        isOpen={isFacilityModalOpen}
        onClose={() => {
          setIsFacilityModalOpen(false)
          setEditingFacility(null)
        }}
        attractionId={selectedAttraction}
        editingFacility={editingFacility}
        onSuccess={handleFacilitySuccess}
      />
    </div>
  )
}